package cn.flant.db.hdle;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("rawtypes")
public class MapHandler implements ResultSetHandler<List<Map>>, RowMapper<Map> {

	public List<Map> handle(ResultSet rs) throws SQLException {
		if (rs == null) {
			return null;
		}
		List<Map> list = new ArrayList<Map>(rs.getFetchSize());
		ResultSetMetaData data = rs.getMetaData();
		int column = data.getColumnCount();
		while (rs.next()) {
			Map<String, Object> values = new HashMap<String, Object>();
			for (int i = 1; i <= column; i++) {
				String name = data.getColumnLabel(i);
				Object value = rs.getObject(i);
				values.put(name.toUpperCase(), value);
			}
			list.add(values);
		}
		return list;
	}

	@Override
	public Map mapRow(ResultSet rs) throws SQLException {
		ResultSetMetaData data = rs.getMetaData();
		int column = data.getColumnCount();
		Map<String, Object> values = new HashMap<String, Object>();
		for (int i = 1; i <= column; i++) {
			String name = data.getColumnLabel(i);
			Object value = rs.getObject(i);
			values.put(name.toUpperCase(), value);
		}
		return values;
	}
}
